package com.whimscrew.store.controller;

import com.whimscrew.store.model.StoreDTO;
import com.whimscrew.store.service.StroeCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("v1/store")
public class StoreController {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StroeCacheService stroeCacheService;

    //获取地区对应的商店
    @GetMapping("{areaCode}/list")
    public Set<StoreDTO> list(@PathVariable String areaCode )   {
        if(redisTemplate.hasKey(areaCode)){
            return (Set<StoreDTO>) redisTemplate.opsForSet().members(areaCode);
        }
        return null;
    }

    //添加商店
    @PostMapping("{areaCode}")
    public String add(@PathVariable String areaCode,@RequestBody StoreDTO dto)   {
        //设置到redis
        redisTemplate.opsForSet().add(areaCode, dto);
        Set<StoreDTO> cacheStores = (Set<StoreDTO>) redisTemplate.opsForSet().members(areaCode);
        stroeCacheService.publishChange("POST",areaCode,cacheStores);
        return  "ok";
    }


}
